<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/8/11
 * Time: 18:10
 */

namespace App\Service;

use App\Models\Member;
use App\Models\Order;
use Illuminate\Support\Facades\DB;

class MemberService
{
    /**
     * 获取会员列表
     * @param array $params
     * @param string $orderBy
     * @param string $sort
     * @param int $page
     * @param int $limit
     * @return \Illuminate\Http\JsonResponse
     */
    public static function getList($params = [],$orderBy = 'id',$sort = 'DESC',$page = 1,$limit = 10)
    {
        $where = [];
//        $memberModel = new Member();
        if(isset($params['nickname']) && empty($params['nickname'])){
            $where[] = ['nickname','like',"%{$params['nickname']}%"];
        }
        $start=($page-1)*$limit;
        $list = Member::where($where)->skip($start)->take($limit)->orderBy($orderBy,$sort)->get()->toArray();
        $count = Member::where($where)->count();
        $pageCount = ceil($count/$limit);
        $data = [
            'list'          => $list,
            'pageCount'     => $pageCount,
        ];
        return Response()->json(['code'=>200,'msg'=>'获取成功','data'=>$data]);
    }

    /**
     * 通过ID获取会员
     * @param int $memberId
     * @return array
     */
    public static function getMemberById($memberId = 0)
    {
        $info = Member::where('id', $memberId)->first(['id', 'nickname', 'avatar', 'openid', 'province', 'city', 'phone','created_at', 'updated_at']);
        $info = $info ? $info->toArray() : [];
        return Response()->json(['code' => 200, 'msg' => '获取成功', 'data' => $info]);

    }

    public static function edit($params = [])
    {
        try{
            $info = Member::where('id',intval($params['id']))->first();
            if(!$info){
                throw new \Exception('该会员不存在');
            }
            $info->avatar       =  trim($params['avatar']);
            $info->nickname     = trim($params['nickname']);
            $info->phone        = trim($params['phone']);
            $info->province     = trim($params['province']);
            $info->city         = trim($params['city']);
            $save = $info->save();
            if(!$save){
                throw new \Exception('修改失败');
            }
        }catch (\Exception $e){
            return Response()->json(['code'=>201,'msg'=>$e->getMessage()]);
        }
        return Response()->json(['code'=>200,'msg'=>'修改成功']);

    }

    public static function destroy($id)
    {
        $idArr = is_array($id) ? $id : [$id];
        if(!$idArr){
            return Response()->json(['code'=>201,'msg'=>'请选择要删除的会员']);
        }
        $del = Member::destroy($idArr);
        if(!$del){
            return Response()->json(['code'=>201,'msg'=>'删除失败']);
        }
        Order::whereIn('mid',$idArr)->delete();
        return Response()->json(['code'=>200,'msg'=>'删除成功']);
    }


}
